package pers.xhh.shopapi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pers.xhh.shopapi.common.Constant;
import pers.xhh.shopapi.common.Mi;
import pers.xhh.shopapi.common.ResultCode;
import pers.xhh.shopapi.dao.MiManagerDao;
import pers.xhh.shopapi.entity.MiManagerEntity;
import pers.xhh.shopapi.entity.MiRoleEntity;
import pers.xhh.shopapi.entity.to.user.MiManagerTo;
import pers.xhh.shopapi.entity.to.user.MiManagerUpdateTo;
import pers.xhh.shopapi.entity.vo.user.MiManagerListVo;
import pers.xhh.shopapi.entity.vo.user.MiManagerVo;
import pers.xhh.shopapi.service.MiManagerService;
import pers.xhh.shopapi.service.MiRoleService;
import pers.xhh.shopapi.util.DateUtils;
import pers.xhh.shopapi.util.Md5Utils;
import pers.xhh.shopapi.util.TokenUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author wei-xhh
 * @date 2020-11-22
 */
@Service
public class MiManagerServiceImpl extends ServiceImpl<MiManagerDao, MiManagerEntity> implements MiManagerService {

    @Autowired
    MiRoleService miRoleService;

    @Override
    public Mi login(String username, String password) {
        if (username.isEmpty() || password.isEmpty()) {
            return Mi.error(ResultCode.ERROR301.getMessage(), ResultCode.ERROR301.getStatus());
        }
        // ->查询用户
        String realPwd = Md5Utils.md5(password);
        QueryWrapper<MiManagerEntity> eq = new QueryWrapper<MiManagerEntity>()
                .eq("mg_name", username)
                .eq("mg_pwd", realPwd);
        MiManagerEntity one = this.getOne(eq);
        if (one == null) {
            return Mi.error(ResultCode.ERROR302.getMessage(), ResultCode.ERROR302.getStatus());
        }

        // ->用户存在,获取token
        String token = TokenUtils.getToken(one);
        MiManagerVo miManagerTo = new MiManagerVo();
        miManagerTo.setId(one.getMgId());
        miManagerTo.setRid(one.getRoleId());
        miManagerTo.setUsername(one.getMgName());
        miManagerTo.setMobile(one.getMgMobile());
        miManagerTo.setEmail(one.getMgEmail());
        miManagerTo.setToken(token);

        // ->返回数据
        return Mi.ok(ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getStatus(), miManagerTo);
    }

    @Override
    public Mi listUser(String query, Integer pagenum, Integer pagesize) {
        if (pagenum == null || pagesize == null) {
            return Mi.error(ResultCode.ERROR303.getMessage(), ResultCode.ERROR303.getStatus());
        }
        if (pagenum <= 0 || pagesize <= 0) {
            return Mi.error(ResultCode.ERROR304.getMessage(), ResultCode.ERROR304.getStatus());
        }

        // ->查询所有用户数据
        // 创建page对象
        Page<MiManagerEntity> pageManager = new Page<>(pagenum, pagesize);
        // 构建条件
        QueryWrapper<MiManagerEntity> wrapper = new QueryWrapper<>();
        if (query != null && !query.isEmpty()) {
            wrapper.like("mg_name", query);
        }
        this.page(pageManager, wrapper);

        long totalpage = pageManager.getTotal();
        List<MiManagerEntity> records = pageManager.getRecords();
        List<MiManagerListVo> collect = records.stream().map(item -> {
            MiManagerListVo miManagerListVo = new MiManagerListVo();
            miManagerListVo.setId(item.getMgId());
            miManagerListVo.setUsername(item.getMgName());
            miManagerListVo.setMobile(item.getMgMobile());
            miManagerListVo.setEmail(item.getMgEmail());
            miManagerListVo.setCreate_time(DateUtils.formatDate(item.getCreateTime()));
            miManagerListVo.setMg_state(item.getMgState() == 1);
            // 查询角色类型
            Integer roleId = item.getRoleId();
            String roleName = "未设置";
            if (roleId == Constant.ROLE_TYPE) {
                roleName = Constant.ROLE;
            } else {
                // 查询
                MiRoleEntity roleEntity = miRoleService.getById(roleId);
                if(roleEntity != null){
                    roleName = roleEntity.getRoleName();
                }
            }
            miManagerListVo.setRole_name(roleName);
            return miManagerListVo;
        }).collect(Collectors.toList());

        // 返回结果
        Map<String, Object> map = new HashMap<>();
        map.put("totalpage", totalpage);
        map.put("pagenum", pagenum);
        map.put("users", collect);

        return Mi.ok(ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getStatus(), map);
    }

    @Override
    public Mi saveMiManagerTo(MiManagerTo miManagerTo) {
        String username = miManagerTo.getUsername();
        String password = miManagerTo.getPassword();
        String email = miManagerTo.getEmail();
        String mobile = miManagerTo.getMobile();

        // 查询用户是否存在
        MiManagerEntity mgName =
                this.getOne(new QueryWrapper<MiManagerEntity>().eq("mg_name", username));
        if (mgName != null) {
            return Mi.error(ResultCode.ERROR306.getMessage(), ResultCode.ERROR306.getStatus());
        }

        // ->注册用户
        MiManagerEntity miManagerEntity = new MiManagerEntity();
        miManagerEntity.setMgName(username);
        miManagerEntity.setMgPwd(Md5Utils.md5(password));
        miManagerEntity.setCreateTime(new Date());
        miManagerEntity.setUpdateTime(new Date());
        if (email != null) {
            miManagerEntity.setMgEmail(email);
        }
        if (mobile != null) {
            miManagerEntity.setMgMobile(mobile);
        }
        boolean save = this.save(miManagerEntity);
        Map<String, Object> map = new HashMap<>();
        if (save) {
            map.put("id", miManagerEntity.getMgId());
            map.put("username", miManagerEntity.getMgName());
            map.put("role_id", -1);
            map.put("create_time", DateUtils.formatDate(miManagerEntity.getCreateTime()));
        }
        return save ? Mi.ok(ResultCode.SUCCESS1.getMessage(), ResultCode.SUCCESS1.getStatus(), map) :
                Mi.error(ResultCode.ERROR305.getMessage(), ResultCode.ERROR305.getStatus());

    }

    @Override
    public Mi updateUserState(Integer uId, Boolean type) {
        if (uId == null || type == null) {
            return Mi.error(ResultCode.ERROR307.getMessage(), ResultCode.ERROR307.getStatus());
        }
        if (uId <= 0) {
            return Mi.error(ResultCode.ERROR308.getMessage(), ResultCode.ERROR308.getStatus());
        }

        // ->更新
        MiManagerEntity miManagerEntity = new MiManagerEntity();
        miManagerEntity.setMgId(uId);
        int state = 0;
        if (type) {
            state = 1;
        }
        miManagerEntity.setMgState(state);
        miManagerEntity.setUpdateTime(new Date());
        boolean b = this.updateById(miManagerEntity);
        Map<String, Object> map = new HashMap<>();
        map.put("id", uId);
        map.put("mg_state", state);

        return b ? Mi.ok(ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getStatus(), map) :
                Mi.error(ResultCode.ERROR309.getMessage(), ResultCode.ERROR309.getStatus());
    }

    @Override
    public Mi getUserById(Integer uId) {
        if (uId == null) {
            return Mi.error(ResultCode.ERROR307.getMessage(), ResultCode.ERROR307.getStatus());
        }
        if (uId <= 0) {
            return Mi.error(ResultCode.ERROR308.getMessage(), ResultCode.ERROR308.getStatus());
        }

        // ->查询
        MiManagerEntity byId = this.getById(uId);
        Map<String, Object> map = new HashMap<>();
        if (byId != null) {
            map.put("id", byId.getMgId());
            map.put("rid", byId.getRoleId());
            map.put("username", byId.getMgName());
            map.put("mobile", byId.getMgMobile());
            map.put("email", byId.getMgEmail());
            return Mi.ok(ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getStatus(), map);
        } else {
            return Mi.error(ResultCode.ERROR310.getMessage(), ResultCode.ERROR310.getStatus());
        }
    }

    @Override
    public Mi updateUserById(Integer uId, MiManagerUpdateTo miManagerUpdateTo) {
        if (uId == null) {
            return Mi.error(ResultCode.ERROR307.getMessage(), ResultCode.ERROR307.getStatus());
        }
        if (uId <= 0) {
            return Mi.error(ResultCode.ERROR308.getMessage(), ResultCode.ERROR308.getStatus());
        }

        // ->更新
        MiManagerEntity miManagerEntity = new MiManagerEntity();
        miManagerEntity.setMgId(uId);
        miManagerEntity.setUpdateTime(new Date());
        String email = miManagerUpdateTo.getEmail();
        String mobile = miManagerUpdateTo.getMobile();
        if (email != null) {
            miManagerEntity.setMgEmail(email);
        }
        if (mobile != null) {
            miManagerEntity.setMgMobile(mobile);
        }

        boolean b = this.updateById(miManagerEntity);
        Map<String, Object> map = new HashMap<>();
        map.put("id", uId);

        return b ? Mi.ok(ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getStatus(), map) :
                Mi.error(ResultCode.ERROR309.getMessage(), ResultCode.ERROR309.getStatus());

    }

    @Override
    public Mi deleteUserById(Integer uId) {
        if (uId == null) {
            return Mi.error(ResultCode.ERROR307.getMessage(), ResultCode.ERROR307.getStatus());
        }
        if (uId <= 0) {
            return Mi.error(ResultCode.ERROR308.getMessage(), ResultCode.ERROR308.getStatus());
        }

        // ->删除
        boolean b = this.removeById(uId);
        Map<String, Object> map = new HashMap<>();
        map.put("id", uId);

        return b ? Mi.ok(ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getStatus(), map) :
                Mi.error(ResultCode.ERROR309.getMessage(), ResultCode.ERROR309.getStatus());
    }

    @Override
    public Mi updateUserRole(Integer uId, Integer rid) {
        if (uId == null || rid == null) {
            return Mi.error(ResultCode.ERROR311.getMessage(), ResultCode.ERROR311.getStatus());
        }
        if (uId <= 0 || rid <= 0) {
            return Mi.error(ResultCode.ERROR312.getMessage(), ResultCode.ERROR312.getStatus());
        }
        // ->更新
        MiManagerEntity miManagerEntity = new MiManagerEntity();
        miManagerEntity.setMgId(uId);
        miManagerEntity.setRoleId(rid);
        miManagerEntity.setUpdateTime(new Date());

        boolean b = this.updateById(miManagerEntity);

        Map<String, Object> map = new HashMap<>();
        map.put("id", uId);
        map.put("rid", rid);

        return b ? Mi.ok(ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getStatus(), map) :
                Mi.error(ResultCode.ERROR309.getMessage(), ResultCode.ERROR309.getStatus());
    }
}
